import cv2
import serial
import numpy as np
from control_hardware import not_screen_and_sensor_command
import time
from datetime import datetime
# s01: 获取标签类别，通过cv2加载cnn，获取中间层
LABELS = open("/home/zhaoqb/A01/VOC/trained_models/classes.names").read().strip().split("\n")
net = cv2.dnn.readNetFromDarknet('/home/zhaoqb/A01/VOC/trained_models/LegoGears.cfg', '/home/zhaoqb/A01/VOC/trained_models/LegoGears_best.weights')
layer = net.getUnconnectedOutLayersNames()

# 定义物品价格
global colaPrice = 2
global spritePrice = 3
global fandaPrice = 3.5
global gumPrice = 2

global colaNum = 0
global spriteNum = 0
global fandaNum = 0
global gumNum = 0





# 3.3 计算物品金额并写入串口屏中。
def WriteScreen():
    change_screen_command('page 7')
    totalNum = colaNum + spriteNum + fandaNum + gumNum
    totalPrice = colaNum * colaPrice + spriteNum * spritePrice + fandaNum * fandaPrice + gumNum * gumPrice
    curTime = str(datetime.now().strftime("%H:%M:%S"))

    send_screen_information_command('t72.txt',colaNum)
    send_screen_information_command('t71.txt',spriteNum)
    send_screen_information_command('t73.txt',fandaNum)
    send_screen_information_command('t707.txt',gumNum)
    
    send_screen_information_command('t713.txt',totalNum)
    send_screen_information_command('t714.txt',totalPrice)
    # todo 识别不出来，也要显示时间吗？
    send_screen_information_command('t715.txt',curTime)


# s02: todo，图像识别函数，
def Recognize_lp(frame):
    
    (H, W) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (640, 640),swapRB=True, crop=False)
    net.setInput(blob)
    layerOutputs = net.forward(layer)
    boxes = []
    confidences = []
    classIDs = []
    # todo

    for output in layerOutputs:
        for detection in output:
            scores = detection[5:]
            classID = np.argmax(scores)
            confidence = scores[classID]
            box = detection[0:4] * np.array([W, H, W, H])
            (centerX, centerY, width, height) = box.astype("int")
            x = int(centerX - (width / 2))
            y = int(centerY - (height / 2))
            boxes.append([x, y, int(width), int(height)])
            confidences.append(float(confidence))
            classIDs.append(classID)
 
    idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.3)
    if len(idxs) > 0:
        for i in idxs.flatten():
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])
            
            
            # todo, 重构切换画面
            if LABELS[classIDs[i]] == 'cola':
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0,255,0), 1, lineType=cv2.LINE_AA)
                text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
                cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5, (0,255,0), 1, lineType=cv2.LINE_AA)
                colaNum = colaNum + 1

                print('cola'str(colaNum))

            elif LABELS[classIDs[i]] == 'sprite': 
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0,255,0), 1, lineType=cv2.LINE_AA)
                text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
                cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5, (0,255,0), 1, lineType=cv2.LINE_AA)
                spriteNum = spriteNum + 1
                print('sprite'str(spriteNum))


            elif LABELS[classIDs[i]] == 'fanda': 
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0,255,0), 1, lineType=cv2.LINE_AA)
                text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
                cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5, (0,255,0), 1, lineType=cv2.LINE_AA)
                fandaNum = fandaNum + 1

                print('fanda'+str(fandaNum))

            elif LABELS[classIDs[i]] == 'gum': 
                cv2.rectangle(frame, (x, y), (x + w, y + h), (255,0,0), 1, lineType=cv2.LINE_AA)
                text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
                cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5, (255,0,0), 1, lineType=cv2.LINE_AA)
                gumNum = gumNum + 1

                print('gum'+str(gumNum))
                
    WriteScreen()
    cv2.imshow('frame',frame)
    cv2.waitKey(0)

# s99: 主函数,
if __name__ == '__main__':
    # 3.3 
    
    # 3.4 确认支付，扫码付款
    
    accept = ''
    while accept == '':
        time.sleep(0.5)
        ser = serial.Serial('/dev/ttyTHS0', 9600, timeout=0.5)
        if ser.isOpen == False:
            ser.open()
        ser.flushInput()
        ser.flushOutput()
        accept = ser.readline()
        accept = str(accept)
        # todo，accept不只是“支付”，其他情况需不需要处理
        if accept == ''
            # 图像识别何屏幕显示
            # 捕获摄像头，0代表笔记本内置摄像头，外置摄像头改为1
            cap = cv2.VideoCapture(0)
            bool condit = True
            while condit:
                # 读取图像，ret表示当前帧是否捕获正确，返回布尔值
                ret, frame = cap.read()
                # todo, 5秒静止，获取图片

                if ret:
                    # 将图像显示出来
                    cv2.imshow("capture", frame)
                # 画面暂停制定毫秒，期间按了键盘则返回按键的ASCII码，否则返回-1

                k = cv2.waitKey(1)
                # 参数为0表示无线等待，代码会阻塞
                # 不调用waitKey，画面只有一片灰色，而且一闪而过
                # 按空格键退出，ord()函数把字母转化为ASCII码
                if k == ord(' '):
                    break
                # 按s键保存
                elif k == ord('s'):
                    # 把图像写入图片
                    cv2.imwrite('yangli' + '.jpg', frame)
                    condit = False

            # 关闭视频捕获器
            cap.release()
            # 销毁所有窗口
            cv2.destroyAllWindows()

            # frame = cv2.imread('18.jpg')
            Recognize_lp(frame)

        elif accept == 'Z1':
            # todo，与3.1一样
            cap = cv2.VideoCapture(0)
            # 3.5
            not_screen_and_sensor_command('C-!')
    